define([
    'Util',
    '../common/getMenu',
    'list',
    'form',
    'text!tpl/weekly/weeklyList.tpl',
    'text!tpl/weekly/commList.tpl',
    'cookie',
    'dialog',
    'select',
    'radios',
    'tab',
    'loading',
    '../common/getPath',
    '../common/getQueryString',
    'date',
    'inputTag',
    "comboSelect",
    '../common/dateFormat'
], function(Util, getMenu, List, Form, tpl,commListTpl, $cookie, Dialog, Select, Radios, Tab, Loading, AjaxPath, GetQueryString, MyDate, inputTag,ComboSelect) {
    require(['style!css/style.css']);
        var _indexModule = null,
            $el = null,
            caseOption = null,
            caseList = null,
            caseTab = null,
            tplId = null,
            initData = null,//处理后数据
            htStarTime = null,//开始日期
            htEndTime = null, //结束日期
            oDataResultBeans = null, //数据
            pageNum = 0,
            pageTotalZ= null,
            htPageSelectLimit = 5, 
            htContractSelect = null,
            UrlstarTime = null,//开始时间的周一
            UrlendTime = null,//开始时间的周日
            submitter = null,//提交人
            submitterId = null,//提交人ID
            serverDate = null,
            htPagejQ = null,
			dialog=null;
    var initialize = function(indexModule, options, tabItem){
    	//console.log(options);
        $el = $(tpl);
        _indexModule = indexModule;
        //caseOption = options;
        caseTab = tabItem;
        this.content = $el;
        tplId = options.menuId;
        //下拉
        peopleSeeclt();
        //点击事件
        eventInit();
    };
    var eventInit = function (){
        //页面除dialog按钮功能
        $el.on('click', '.t-list-title', htConfiguration);//折叠
        //$el.on('click', '.btnSearch', htConfiguration);//折叠
        $el.on('change','.selectPerPage',htPageSelect)//
        $el.on('click','.btnSearch',initAscquireData)//查询
        $el.on('click','.weekEdit',editWeekly)//编辑
        $el.on('click','.weekSubmit',weekSubmit)//提交
        $el.on('click','.btnReset',btnReset)//重置
        $el.on('click','.htPageConent .prevPage',htPrevPage)//上一页
        $el.on('click','.htPageConent .tcdNumber ',htTcdNumberPage)//当前页
        $el.on('click','.htPageConent .nextPage',htNextPage)//下一页
        
    };
    //下拉
    var peopleSeeclt = function(){
    	 //Util.ajax.getJson("http://192.168.91.177:8092/weekly/week/userRole/"+$cookie.get("userId"),{}, function(result, isok) {
    	Util.ajax.getJson(AjaxPath.weekly+"/week/userRole/"+$cookie.get("userId"),{}, function(result, isok) {
    		if(result.returnCode === "0000"){
	    		//服务器时间
				serverDate = result.beans.endTime;
				htStarTime = htDayDate().htStarTime;//
				htEndTime = htDayDate().htEndTime;//现在时间
		        if(result.beans.sucess === '领导'){
		        	var config = {
					    el:$(".peopleSeeclt", $el),       //要绑定的容器
					    name:'peopleSeeclt',    //下拉框单元添加name属性
					    checked:'0',//默认选中
					    textField:"userName",
					    valueField:"userId",
					    //url:'../data/select.json',  //数据源，不建议使用，后期将会移除
					    datas: result.beans.userList         //数据源与url模式可二选一
					}
					htContractSelect = new ComboSelect(config);
					htContractSelect.setValue($cookie.get("userId"));
    				submitterId = htContractSelect.getSelected().userId;
					htContractSelect.change(function(e){
						submitterId = e.target.value;
					})
    			}else{
    				$('.orderWaterCode',$el).val(result.beans.sysUser.userName);
    				submitter =result.beans.sysUser.userName;
    				submitterId = result.beans.sysUser.userId;
    			}
    			//日期范围
    			htDateScopeFn();
    			//初始化
    			initAscquireData(0,5);
	       }else{
    			new Dialog({
                    mode: 'confirm', // 对话框模式，默认normal标准|confirm浮动层|confirm确认对话框
                    title: '提示',
                    width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                    height: 120, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                    cancelDisplay: false, //是否显示取消按钮（强制执行，可在confirm模式下生效），可选项。 默认true(显示)
                    modal: true,
                    content: '<div style="text-align:center;margin-top:50px">' + result.returnMessage + '</div>'// 对话框内容，可以是字符串、html片段、或dom对象,默认为loading状态（点组成的圈）
                });
    		}
    	});
    }
     //日期范围
    var htDateScopeFn = function(){
    	htStarTime = htDayDate().htStarTime;
    	htEndTime = htDayDate().htEndTime;;
    	var doubleDates = new MyDate({
		    el:$('.htDateScope',$el),
		    label:'日期范围:',
		    double:{    //支持一个字段里显示两个日期选择框
		        start:{
		            name:'startTime',
		            inputClassName:'',
		            format: 'yyyy-MM-dd',
		            type:'date',
		            defaultValue:htStarTime,
		            hmsflag:false,
		            inputPlaceholder:"请选择",
		            btns:['now', 'confirm'],
		            isReadOnly:false,  //项可设置日期输入框是否只读
		            done: function(datas,value,endDate){
		                doubleDates.options.double.end.min = datas;    //设置结束日期的最小限制
		               	htStarTime = datas;
		            }
		        },
		        end:{
		            name:'endTime',
		            inputClassName:'',
		            format: 'yyyy-MM-dd',
		            type:'date',
		            defaultValue:htEndTime,
		            inputPlaceholder:"请选择",
		            value:htEndTime,
		            btns:['now', 'confirm'],
		            isReadOnly:false,  //项可设置日期输入框是否只读
		            done: function(datas,value){
		                doubleDates.options.double.start.max = datas;  //设置开始日期的最大日期
		            	htEndTime = datas;
		            }
		        }
		    }
		    //zzfhDateDate.options.min=nowTime(0,'yyyy-MM-dd');
		    
		});
		doubleDates.options.double.start.max = htEndTime;
		doubleDates.options.double.end.max = htEndTime;
		doubleDates.options.double.end.min = htStarTime;
		
		
    };
  	
  	//编辑
  	var editWeekly = function(data){
  		var odata = '';
  		var weeknum = $(this).attr('weeknum')-0;
  		var weekyear = $(this).attr('weekyear'); 
  		for(var i=0,len =oDataResultBeans.length;i<len;i++){
  			if(weeknum === oDataResultBeans[i].weekNum && weekyear === oDataResultBeans[i].weekYear){
  				odata = oDataResultBeans[i];
  			}
  		};
  		//odata.submitter = submitter;
  		odata.submitterId = submitterId;
  		require(['js/weekly/editWeek'], function(editOrderContent) {
            var result = new editOrderContent({}, odata, caseTab);
            caseTab.content(result.content);
        });
  	}
  	//提交
  	var weekSubmit = function(id){
  		var _this = this;
  		 Util.ajax.getJson(AjaxPath.weekly+"/week/updateStates/"+$(this).attr('idweek'),{}, function(result, isok) {
    		if(result.returnCode === "0000"){
                new Dialog({
                    mode: 'tips',
                    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
                    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
                    width:320,
                    height:180,
                    content: '<div style="text-align:center;margin-top:90px">' + result.returnMessage + '</div>'
                });
                $(_this).parent().parent().siblings().find('.statusStr').html('&nbsp;&nbsp;已提交');
                $(_this).parent().parent().siblings().find('.tri-down').removeClass('tri-down').addClass('tri-left');
                $(_this).parent().parent().hide(100);
                $(_this).parent().html('');
	       }else{
    			new Dialog({
                    mode: 'confirm', // 对话框模式，默认normal标准|confirm浮动层|confirm确认对话框
                    title: '提示',
                    width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                    height: 120, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                    cancelDisplay: false, //是否显示取消按钮（强制执行，可在confirm模式下生效），可选项。 默认true(显示)
                    modal: true,
                    content: '<div style="text-align:center;margin-top:50px">' + result.returnMessage + '</div>'// 对话框内容，可以是字符串、html片段、或dom对象,默认为loading状态（点组成的圈）
                });
    		}
    		
    	});
  	}
  	//重置
  	
  	var btnReset = function(){
  		if(htContractSelect !== null){
        	htContractSelect.setValue($cookie.get("userId"));
        	//submitter = $cookie.get("userName");
        }
  		submitterId = $cookie.get("userId");
  		//日期范围
        htDateScopeFn();
        //初始化
        initAscquireData(0,5);
  	}
  	//初始化
  	var initAscquireData = function(pageNum0,limit){
  		var htStarTimes = new Date(htStarTime).getTime();
  		var htEndTimes = new Date(htEndTime).getTime();
  		UrlstarTime = htWeekDays(htStarTimes)[0];
  		UrlendTime  = htWeekDays(htEndTimes)[6];
  		Util.ajax.getJson(AjaxPath.weekly+"/week/weekList?submitter="+submitterId+"&startTime="+UrlstarTime+"&endTime="+UrlendTime+"&userId="+$cookie.get("userId"),{}, function(result, isok) {
    		if(result.returnCode === "0000"){
    			//$('.htPageqq',$el).html(result.beans[4].weekContentList[0].weekContent)
    			//返回数据初步处理  反转
    			oDataResultBeans = result.beans.reverse();
    			//处理后数据
    			initData = oDataPage(oDataResultBeans,5);
    			//计算总共页数
    			pageNum = Math.ceil(result.bean.total / 5);
    			//总条数
    			pageTotalZ = result.bean.total;
    			
    			//htPageSelectLimit
    			//显示第第1页    一页 5条数据
    			initDataNoUrl(0,5); 
    			//设置总条数
    			$('.ht_famBoldcol .sn-list-pagination .total').html('共'+result.bean.total+'条');
    			$('.selectValBox .selectVal',$el).html(5);
    			$('.per-page .selectPerPage',$el).val(5)
    			//分页显示 pageNum页码总    默认显示第一页
    			htPagejQ(pageNum,1);//htPagejQ(总共pageNum页,默认显示第1页);
    		}else{
    			new Dialog({
                    mode: 'confirm', // 对话框模式，默认normal标准|confirm浮动层|confirm确认对话框
                    title: '提示',
                    width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                    height: 120, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                    cancelDisplay: false, //是否显示取消按钮（强制执行，可在confirm模式下生效），可选项。 默认true(显示)
                    modal: true,
                    content: '<div style="text-align:center;margin-top:50px">' + result.returnMessage + '</div>'// 对话框内容，可以是字符串、html片段、或dom对象,默认为loading状态（点组成的圈）
                });
    		}
		});
  	}
  	
  	var initDataNoUrl = function(pageNum0,limit){
  		var htmls = '';
		var initDataFor = oDataPage(oDataResultBeans,limit)[pageNum0];
		for(var i = 0;i<initDataFor.length;i++){
			if(initDataFor[i].weekContentList === null){
				initDataFor[i].weekContentList = []
				htmls += muban(initDataFor[i]);
			}else{
				htmls += muban(initDataFor[i]);
			}
		}
		$('.conentList',$el).html(htmls);
  	}
  	
  	//模板
    var muban = function(oDataArr){
    	if(oDataArr.weekContentList.length ===0){
    		for(var i=0,len= htWeekDays(oDataArr.startTime).length;i<len;i++){
    			var obj = {weekTime:htWeekDays(oDataArr.startTime)[i]}
    			oDataArr.weekContentList.push(obj);
    		}
    	}else{
    		for(var i=0;i<oDataArr.weekContentList.length;i++){
			    oDataArr.weekContentList[i].weekTime = timeStamp(oDataArr.weekContentList[i].weekTime)
    		}
    		for(var i=oDataArr.weekContentList.length,len= htWeekDays(oDataArr.startTime).length;i<len;i++){
    			var obj = {weekTime:htWeekDays(oDataArr.startTime)[i]}
    			oDataArr.weekContentList.push(obj);
    		}
    	}
    	var oData = {}
    	oData.Mon = oDataArr.weekContentList[0];
    	oData.Tue = oDataArr.weekContentList[1];
    	oData.Wed = oDataArr.weekContentList[2];
    	oData.Thu = oDataArr.weekContentList[3];
    	oData.Fri = oDataArr.weekContentList[4];
    	oData.Sat = oDataArr.weekContentList[5];
    	oData.Sun = oDataArr.weekContentList[6];
    	var statusStr = '';
    	switch(oDataArr.status){
			case 0:
			  	statusStr = '未填写' ;
				break;
			case 1:
				statusStr = '已填写，未提交' ;
				break;
			case 2:
				statusStr = '已提交'; 
				break;
			default:
				statusStr = '';
		}
    	var statusButton = '';
    	var userIds = $cookie.get("userId")-0;
    	var submitterIds = submitterId -0;
    	if(userIds === submitterIds){
    		switch(oDataArr.status){
				case 0:
				  	statusButton =	'<a href="javascript:;" class="t-btn t-btn-white t-btn-xs weekEdit" status='+oDataArr.status+' startTime = '+oDataArr.startTime+' endTime = '+oDataArr.endTime+' weekNum = '+oDataArr.weekNum+' weekYear = '+oDataArr.weekYear+' id = '+oDataArr.id+'>&nbsp;&nbsp;编 辑&nbsp;&nbsp;</a>'
					break;
				case 1:
					statusButton =	'<a href="javascript:;" class="t-btn t-btn-white t-btn-xs weekEdit" startTime = '+oDataArr.startTime+' endTime = '+oDataArr.endTime+' weekNum = '+oDataArr.weekNum+' weekYear = '+oDataArr.weekYear+' id = '+oDataArr.id+'>&nbsp;&nbsp;编 辑&nbsp;&nbsp;</a>'+
									'<a href="javascript:;" class="t-btn t-btn-white t-btn-xs weekSubmit ml-10" idWeek= "'+oDataArr.id+'">&nbsp;&nbsp;提 交&nbsp;&nbsp;</a>'
					break;
				default:
					statusButton ='';
			}
    	}
    	var htmls = '<div><div class="t-list-title ht_botrgba220">'+
						'<h2 class="ht_famBoldcol">'+					
							'<i class="icon-circle"></i>'+
							'<span style="color: #63a8eb;">&nbsp;&nbsp;'+oDataArr.weekYear+' 年</span>'+
							'<span style="color: #63a8eb;"> 第  '+oDataArr.weekNum+' 周</span>'+
							'<span class="ml-10" style="color: #63a8eb;">'+timeStamp(oDataArr.startTime)+'&nbsp;&nbsp;~&nbsp;&nbsp;'+timeStamp(oDataArr.endTime)+'</span>'+ 
							'<span class="statusStr" style="color: #63a8eb;"> &nbsp;&nbsp;' + statusStr + '</span>'+     
						'</h2>'+
						'<span class="tri '+(oDataArr.status === 2 ? "tri-left" : "tri-down")+'"></span>'+
					'</div>'+
					'<div class="" style="border: 1px solid #eee; border-top: 0;'+(oDataArr.status === 2 ? "display: none;" : "")+'">'+
						'<div class="mt-10 ml-10 statusButton">'+statusButton+'</div>'+
						'<div class="mt-10">'+Util.hdb.compile(commListTpl)(oData)+'</div>'+
					'</div></div>'
		return 	htmls;		
    }
	//时间戳转换成时间
    var timeStamp = function(timestamp){
    	var timestampint = 0;
    		if(!isNaN(timestamp)){
    			timestampint = timestamp
    		}else{
    			var oodate = timestamp.replace("-", "/").replace("-", "/");
    			timestampint = new Date(oodate)
    		}
    	   	var date = new Date(timestampint);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
	        //var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
	        Y = date.getFullYear() + '-';
	        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
	        D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
	        h = date.getHours() + ':';
	        m = date.getMinutes() + ':';
	        s = date.getSeconds();
	        return Y+M+D;
    }
    //日期转化到某一天
    var htDayDate = function(num){
    	var Num = -28;
    	Date.prototype.Format = function (fmt) {
	    var o = {
	        "M+": this.getMonth() + 1, //月份
	        "d+": this.getDate(), //日
	        "h+": this.getHours(), //小时
	        "m+": this.getMinutes(), //分
	        "s+": this.getSeconds(), //秒
	        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
	        "S": this.getMilliseconds() //毫秒
	    };
		    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
		    for (var k in o)
		        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		    return fmt;
		}
   		var htEndTime = new Date(serverDate).Format("yyyy-MM-dd");//Format("输入你想要的时间格式:yyyy-MM-dd,yyyyMMdd")
		var date=new Date(serverDate)//获取当前时间
		date.setDate(date.getDate() + Num);//设置天数 num天
		var htStarTime = date.Format("yyyy-MM-dd");
		return {"htStarTime":htStarTime,"htEndTime":htEndTime}
    }
    
    //当前周有那几天
    var htWeekDays = function(timestamp){//时间戳
    	var weekDays = [];
    	d =new Date((timestamp-0));
		nowYear = d.getYear();
		nowYear += (nowYear < 2000) ? 1900 : 0;
		w = d.getDay();
		n = (w == 0 ? 7 : w) - 1;
		d.setDate(d.getDate() - n);
		for(i=0; i<7; i++) {
			var dates = nowYear + '-' + (d.getMonth()+1) + '-' + d.getDate()
		 	weekDays.push(timeStamp(dates));
		 	d.setDate(d.getDate() + 1);
		}
		return weekDays
    }
   
    
    //分页
    var htPageSelect = function(){
    	$('.selectValBox .selectVal',$el).html(this.value);
    	htPageSelectLimit = this.value-0;
    	initDataNoUrl(0,htPageSelectLimit);
    	pageNum = Math.ceil(pageTotalZ / htPageSelectLimit);//总页数
    	htPagejQ(pageNum,1);//htPagejQ(总共pageNum页,默认显示第1页);
    }
    //上一页
    var htPrevPage = function(){
    	var current = parseInt($('.htPageConent',$el).children("span.current").text());
    	if(current>1){
    		htPagejQ(pageNum,current-1);
    		initDataNoUrl(current-2,htPageSelectLimit);
    	}
    }
    //当前页
    var htTcdNumberPage = function(){
    	var current = parseInt($(this).text());
    	htPagejQ(pageNum,current);
    	initDataNoUrl(current-1,htPageSelectLimit);
    }
    //下一页
    var htNextPage = function(){
    	var current = parseInt($('.htPageConent',$el).children("span.current").text());
    	if(current< pageNum){
    		htPagejQ(pageNum,current+1);
    		initDataNoUrl(current,htPageSelectLimit);
    	}
    }
    //数据分页处理
    var oDataPage = function(oData,em){
    	var Em = em-0
    	var oDataArr = [];
    	for(var i=0;i<oData.length;i+=Em){
		    oDataArr.push(oData.slice(i,i+Em));
		}
    	return oDataArr
    }
    //折叠 
    var htConfiguration = function(){
    	$(this).children('.tri').toggleClass("tri-left").toggleClass("tri-down");
        $(this).siblings().stop().slideToggle(100);
    }
    //分页插件
    var htPagejQ = function(page,limit){
    	require(['js/weekly/jquerypagehu'],function(){
    		$('.htPageConent',$el).createPagess({
		        pageCount:page,
		        current:limit
			});
			if(limit>1){$('.htPageConent .prev',$el).addClass('htActive');}else{$('.htPageConent .next',$el).removeClass('htActive');};
			if(limit<page){$('.htPageConent .next',$el).addClass('htActive');}else{$('.htPageConent .next',$el).removeClass('htActive');};
    	});
    }
    return initialize;
});